package com.itheima.model.search.listenter;

import com.alibaba.fastjson.JSON;
import com.heima.model.kafka.message.KafkaMessageConstants;
import com.heima.model.searchVo.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class SyncArticleListener {

    @Resource
    private RestHighLevelClient client;

    @KafkaListener(topics = KafkaMessageConstants.AP_ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message){
        if (StringUtils.isEmpty(message)){
            return;
        }
            log.info("SyncArticleListener,message={}",message);
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
            //通过kafka获取到数据之后进行添加到es
            IndexRequest indexRequest=new IndexRequest("app_article_info");
            indexRequest.id(searchArticleVo.getId().toString());
            indexRequest.source(message, XContentType.JSON);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
           log.error("sync es error={}", e);
        }
    }

}
